<?php
$pageTitle = "登录";
$currentPage = "login";
// include('../star/resource/navbar.php');
include('./headers.php');
include('./db/conn.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $account = $_POST['account'];
    $password = $_POST['password'];

    // 对用户输入进行安全处理，如防止 SQL 注入等
    $account = mysqli_real_escape_string($conn, $account);

    // 检查用户是否存在
    $sql = "SELECT * FROM user WHERE account='$account' AND is_deleted=FALSE";
    $result = $conn->query($sql);

    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();

        // 验证密码
        if ($password == $user['password']) {
            // 用户验证成功，设置cookie
            setcookie('user_id', $user['user_id'], time() + (86400 * 30), "/"); // 设置为30天有效期
            setcookie('role', $user['role'], time() + (86400 * 30), "/");
            setcookie('username', $user['username'], time() + (86400 * 30), "/");
            header("Location: ./search.php");
            exit();
        } else {
            echo "登录失败，请检查账号和密码。";
        }
    } else {
        echo "登录失败，请检查账号和密码。";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
    <link rel="stylesheet" href="./star/resource/css/styles.css">
</head>
<body>
    <div class="container">
        <h2>用户登录</h2>
        <form method="post" action="">
            <label for="account">账号:</label>
            <input type="account" id="account" name="account" required><br>
            
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" required><br>
            
            <input type="submit" value="登录">
        </form>
        <p>还没有账号？ <a href="register.php">注册</a></p>
    </div>
</body>
<style scoped>
</style>
</html>
